<!-- src/views/student/ApplyPosition.vue -->
<template>
  <div class="apply-position">
    <el-page-header @back="goBack">
      <template #content>
        <span class="title">申请岗位</span>
      </template>
    </el-page-header>

    <el-card class="application-card">
      <template #header>
        <div class="card-header">
          <h3>岗位信息</h3>
        </div>
      </template>

      <div v-if="position" class="position-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="企业名称">{{ position.companyName }}</el-descriptions-item>
          <el-descriptions-item label="岗位名称">{{ position.title }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">{{ position.department }}</el-descriptions-item>
          <el-descriptions-item label="工作地点">{{ position.workLocation }}</el-descriptions-item>
          <el-descriptions-item label="薪资范围">{{ position.salaryRange }}</el-descriptions-item>
          <el-descriptions-item label="工作类型">{{ getWorkTypeLabel(position.workType) }}</el-descriptions-item>
          <el-descriptions-item label="截止日期">{{ formatDate(position.deadline) }}</el-descriptions-item>
        </el-descriptions>

        <div class="description-section">
          <h4>岗位描述</h4>
          <div v-html="position.description || '暂无描述'" class="html-content"></div>
        </div>

        <div class="requirements-section">
          <h4>岗位要求</h4>
          <div v-html="position.requirements || '暂无要求'" class="html-content"></div>
        </div>
      </div>
    </el-card>

    <el-card class="application-form-card">
      <template #header>
        <div class="card-header">
          <h3>申请信息</h3>
        </div>
      </template>

      <el-form
        :model="applicationForm"
        :rules="applicationRules"
        ref="applicationFormRef"
        label-width="120px"
      >
        <el-form-item label="简历" prop="resumeUrl">
          <el-input v-model="applicationForm.resumeUrl" placeholder="请输入简历链接">
            <template #append>
              <el-button @click="uploadResume">上传简历</el-button>
            </template>
          </el-input>
          <div class="upload-tip">您可以上传简历文件，或提供已有的简历链接</div>
        </el-form-item>

        <el-form-item label="求职信" prop="coverLetter">
          <el-input
            v-model="applicationForm.coverLetter"
            type="textarea"
            :rows="6"
            placeholder="请输入求职信内容"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitApplication" :loading="submitLoading">
            提交申请
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 简历上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传简历"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        action="/api/students/resume"
        :on-success="handleResumeUploadSuccess"
        :on-error="handleResumeUploadError"
        :file-list="fileList"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传PDF或Word格式的简历文件，大小不超过10MB
          </div>
        </template>
      </el-upload>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStudentStore } from '../../store/student'
import { commonApi } from '../../api/common'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const studentStore = useStudentStore()

const position = ref(null)
const submitLoading = ref(false)
const uploadDialogVisible = ref(false)
const fileList = ref([])
const applicationFormRef = ref()

// 申请表单
const applicationForm = reactive({
  positionId: null,
  resumeUrl: '',
  coverLetter: ''
})

// 表单验证规则
const applicationRules = {
  resumeUrl: [
    { required: true, message: '请输入简历链接或上传简历', trigger: 'blur' }
  ],
  coverLetter: [
    { required: true, message: '请输入求职信内容', trigger: 'blur' }
  ]
}

// 获取岗位详情
const fetchPositionDetail = async (positionId) => {
  try {
    const response = await commonApi.getPositionDetail(positionId)
    position.value = response.data
    applicationForm.positionId = positionId
  } catch (error) {
    ElMessage.error('获取岗位详情失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取工作类型标签
const getWorkTypeLabel = (workType) => {
  switch (workType) {
    case 1: return '全职'
    case 2: return '兼职'
    case 3: return '实习'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 打开简历上传对话框
const uploadResume = () => {
  uploadDialogVisible.value = true
}

// 处理简历上传成功
const handleResumeUploadSuccess = (response, file) => {
  if (response && response.data && response.data.resumeUrl) {
    applicationForm.resumeUrl = response.data.resumeUrl
    ElMessage.success('简历上传成功')
    uploadDialogVisible.value = false
  } else {
    ElMessage.error('简历上传失败')
  }
}

// 处理简历上传失败
const handleResumeUploadError = (error) => {
  ElMessage.error('简历上传失败: ' + (error.response?.data?.message || '未知错误'))
}

// 提交申请
const submitApplication = async () => {
  if (!applicationFormRef.value) return

  await applicationFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const applicationData = {
          positionId: applicationForm.positionId,
          resumeUrl: applicationForm.resumeUrl,
          coverLetter: applicationForm.coverLetter
        }

        await studentStore.submitApplication(applicationData)
        ElMessage.success('实习申请提交成功')
        router.push('/student/applications')
      } catch (error) {
        ElMessage.error('申请提交失败: ' + (error.response?.data?.message || error.message))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  const positionId = route.params.id
  if (positionId) {
    fetchPositionDetail(positionId)
  } else {
    ElMessage.error('岗位信息错误')
    router.push('/student/positions')
  }
})
</script>

<style scoped>
.apply-position {
  padding: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.card-header h3 {
  margin: 0;
}

.position-info {
  margin-bottom: 20px;
}

.description-section,
.requirements-section {
  margin-top: 20px;
}

.description-section h4,
.requirements-section h4 {
  margin-bottom: 10px;
}

.html-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.application-card,
.application-form-card {
  margin-bottom: 20px;
}
</style>
